package com.taptech.doufu.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.view.View
import android.widget.RelativeLayout
import com.taptech.doufu.R
import com.taptech.doufu.model.user.UserPosterBean
import com.taptech.doufu.presenter.user.IUserPosterView
import com.taptech.doufu.presenter.user.UserPosterPresenter
import com.taptech.doufu.ui.activity.base.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_user_poster.*
import android.graphics.Canvas
import android.widget.Toast
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.net.retrofit.api.RxJavaHelper
import com.taptech.doufu.ui.view.WaitDialog
import com.taptech.doufu.util.*
import kotlinx.android.synthetic.main.activity_user_poster.ivUserHead
import kotlinx.android.synthetic.main.activity_user_poster.tvUserName
import kotlinx.android.synthetic.main.view_user_post_sum_info.*
import rx.Observable
import java.util.concurrent.TimeUnit


class UserPosterActivity : BaseMvpActivity<UserPosterPresenter>(),IUserPosterView{
    private var waitDialog:WaitDialog? = null
    override fun initPresenter(intent: Intent) {
        mPresenter = UserPosterPresenter(this,this,intent)
        waitDialog = WaitDialog(this,R.style.updateDialog)
        waitDialog?.show()
        mPresenter.getUserPoster()

    }

    override fun initView() {
        lineSumLeft.visibility = View.GONE
        lineSumRight.visibility = View.GONE
        layBack.setOnClickListener {
            finish()
        }
        layWeixin.setOnClickListener {
            share(ShareType.Weixin)
        }
        layQQ.setOnClickListener {
            share(ShareType.QQ)
        }
        layWeibo.setOnClickListener {
            share(ShareType.Weibo)
        }
        layDownload.setOnClickListener {
            download()
        }

    }

    override fun getLayout(): Int {
        return R.layout.activity_user_poster
    }

    override fun getUserPosterResult(success:Boolean,detail: UserPosterBean) {
        if (success) {
            ivQRCode.setImageBitmap(ZXingUtils.createQRImage(detail.shareUrl,ScreenUtil.dip2px(this,64f),ScreenUtil.dip2px(this,64f)))
            val userInfo = detail.userInfo
            GlideUtil.displayCircleImage(ivUserHead, userInfo.head_image)
            val novel = detail.novelInfo
            tvUserName.text = userInfo.nickname
            tvUserDesc.text = if (detail.isSignedAuthor) "（豆花签约作家）" else "（豆花作家）"
            tvLength.text = detail.length.toString()
            tvCollectCount.text = detail.fans_counts.toString()
            GlideUtil.displayRoundImage(ivCover, novel.with_image_w, 5)
            tvTitle.text = novel.topic_title
            tvTip.text = novel.tipTxt
            tvDesc.text = StringUtil.filterLineFeed(novel.description)
            if (novel.tags.size > 0) {
                tvTag1.text = novel.tags[0].name
                tvTag1.visibility = View.VISIBLE
            }else{
                tvTag1.visibility = View.GONE
            }
            if (novel.tags.size > 1) {
                tvTag2.text = novel.tags[1].name
                tvTag2.visibility = View.VISIBLE
            }else{
                tvTag2.visibility = View.GONE
            }
            Observable.timer(1500,TimeUnit.MILLISECONDS)
                    .compose(RxJavaHelper.observeOnMainThread())
                    .subscribe {
                        createPic()
                        waitDialog?.dismiss()
                    }
        }else{
            //错误提示
            waitDialog?.dismiss()
            Toast.makeText(this,"海报生成失败，请重试",Toast.LENGTH_LONG).show()
        }
    }

    private fun createPic() {
        val bitmap = getViewBitmap(layContent)

        val screenHeight = ScreenUtil.getScreenHeight(this)
        val screenWidth = ScreenUtil.getScreenWidth(this)
        val viewWidth = screenWidth-ScreenUtil.dip2px(this,54f)
        val viewHeight = (screenHeight-ScreenUtil.dip2px(this,94f+88f))
        if (bitmap != null) {
            val picScale = bitmap.height.toFloat()/bitmap.width.toFloat()
            val viewScale = viewHeight.toFloat()/viewWidth.toFloat()
            if (picScale > viewScale) {
                val width = (bitmap.width*(viewHeight.toFloat()/bitmap.height.toFloat())).toInt()
                val params = RelativeLayout.LayoutParams(width,viewHeight)
                params.addRule(RelativeLayout.CENTER_HORIZONTAL)
                //高度固定，宽度自适应
                ivBigPic.layoutParams = params
            }
            ivBigPic.setImageBitmap(bitmap)
        }
    }



    fun share(type:Int) {
        val bitmap = getViewBitmap(layContent)
        ShareUtils.shareBigPic(this,type,bitmap)
    }

    fun download() {
        val bitmap = getViewBitmap(layContent)
        if (bitmap == null) {
            Toast.makeText(this, "图片已保存失败", Toast.LENGTH_SHORT).show()
        }
        val res = FileUtil2.saveImageToGallery(this,bitmap,"${System.currentTimeMillis()}.jpg")
        if (res) {
            Toast.makeText(this, "图片已保存至相册", Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(this, "图片已保存失败", Toast.LENGTH_SHORT).show()
        }
    }


    var bitmap:Bitmap? = null

    private fun getViewBitmap(view: View): Bitmap? {
        if (bitmap != null) {
            return bitmap
        }

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.RGB_565)
        bitmap?.density = resources.displayMetrics.densityDpi
        val canvas = Canvas(bitmap!!)
        view.draw(canvas)
        return bitmap
    }

    companion object{
        fun startActivity(context: Context,uid:Int) {
            val intent = Intent(context,UserPosterActivity::class.java)
            intent.putExtra(Constant.UID,uid)
            context.startActivity(intent)
        }

        fun startActivity(context: Context, uid: Int, userPosterBean: UserPosterBean) {
            val intent = Intent(context,UserPosterActivity::class.java)
            intent.putExtra(Constant.DATA,userPosterBean)
            intent.putExtra(Constant.UID,uid)
            context.startActivity(intent)
        }
    }
}